package com.lanp.native_test.config.database;

import com.lanp.native_test.common.DataSourceCSV;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author jiangpeng
 * Created with IntelliJ IDEA.
 * Description:  动态数据源
 * Date: 2022-03-04 16:03:37
 */
@Configuration
public class DynamicDataSourceConfig {


    @Bean
    @Primary
    public DataSource primaryDataSource(@Autowired Map<String, DataSource> baseDataSourceMap) {
        System.out.println("create routing datasource...");
        Map<Object, Object> map = new HashMap<>();
        //获取主数据源
        DataSource masterDataSource = baseDataSourceMap.get(DataSourceCSV.masterDataSource);
        //设置批量数据源
        map.putAll(baseDataSourceMap);
        RoutingDataSource routing = new RoutingDataSource();
        routing.setTargetDataSources(map);
        routing.setDefaultTargetDataSource(masterDataSource);
        return routing;
    }
}
